﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Util;
using LBKDHelper.Models;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin.OperationPlugins
{
    [Description("重置货运单的运输状态（挂载到货运单的保存或审核操作）"), HotUpdate]
    public class ResetDeliveryStatePlugin : AbstractOperationServicePlugIn
    {
        #region MyRegion

        readonly ElementKeySchema F_RDLV_BillStatus = new ElementKeySchema
        {
            DbKey = "F_RDLV_BILLSTATUS",
            FormKey = "F_RDLV_BillStatus",
            OrmKey = "F_RDLV_BillStatus"
        };

        #endregion

        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            e.FieldKeys.Add(F_RDLV_BillStatus.FormKey);
        }

        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);

            if (FormOperation.OperationId == Kingdee.BOS.Core.Metadata.FormElement.FormOperation.Operation_Save
                || FormOperation.OperationId == Kingdee.BOS.Core.Metadata.FormElement.FormOperation.Operation_Audit)
            {
                var selectedRows = e.SelectedRows;
                foreach (var row in selectedRows)
                {
                    ResetDeliveryState(row);
                }
            }
        }

        private void ResetDeliveryState(ExtendedDataEntity row)
        {
            var rowData = row.DataEntity;
            var billId = rowData["Id"]?.ToString();
            if (string.IsNullOrEmpty(billId))
            {
                return;
            }

            // 是否存在发货通知单
            var existNoticeOrder = DBUtils.ExecuteScalar(Context, $@"/*dialect*/
                select top 1
	                1
                from RDLV_t_DiliveOrdEntry as a
                inner join RDLV_t_DiliveOrdEntry_LK as b on b.FSTableName = 'T_SAL_DELIVERYNOTICEENTRY'
                    and b.FEntryID = a.FEntryID
                where a.FID = {billId};", 0);
            if (existNoticeOrder != 1)
            {
                // 不存在发货通知单，说明不是销售货运单，则不处理其货运状态
                return;
            }

            var outStockState = DBUtils.ExecuteScalar<string>(Context, $@"/*dialect*/
                select top 1
	                '1'
                from RDLV_t_DiliveOrdEntry as a
                inner join RDLV_t_DiliveOrdEntry_LK as b on b.FSTableName = 'T_SAL_DELIVERYNOTICEENTRY'
                    and b.FEntryID = a.FEntryID
                inner join T_SAL_OUTSTOCKENTRY_LK as c on c.FSTABLENAME = 'T_SAL_DELIVERYNOTICEENTRY'
                    and c.FSID = b.FSId
                inner join T_SAL_OUTSTOCKENTRY as d on d.FENTRYID = c.FENTRYID
                inner join T_SAL_OUTSTOCK as e on e.FID = d.FID
                where e.FDOCUMENTSTATUS = 'C'
                and a.FID = {billId};", default);

            var deliveryState = string.IsNullOrEmpty(outStockState) ? "A" : "B";
            DBUtils.Execute(Context, $@"update RDLV_t_DiliveOrder
                set F_RDLV_BILLSTATUS = '{deliveryState}'
                where FID = {billId};");
        }
    }
}
